﻿using DataBase.Intarstructure.Imtarment;
using Intarstructure;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace DataBase.Intarstructure.Implature
{
    /// <summary>
    /// 仓储
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseRepository<T> :IBaseRepository<T> where T : class
    {
        TMSDbContext db;
        public BaseRepository(TMSDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 无条件查询
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> AllShow()
        {
            return db.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 多条件查询
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> AllShow(Expression<Func<T,bool>> expression)
        {
            return db.Set<T>().Where(expression).AsQueryable();
        }
        /// <summary>
        /// 单条件查询
        /// </summary>
        /// <returns></returns>
        public async Task<T> OnlyShow(Expression<Func<T, bool>> expression)
        {
            return await db.Set<T>().Where(expression).FirstOrDefaultAsync();
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task<int> AsyncAdd(T item)
        {
            await db.Set<T>().AddAsync(item);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task<int> AsyncUpdate(T item)
        {
            db.Set<T>().Update(item);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task<int> AsyncRangeAdd(List<T> item)
        {
            await db.Set<T>().AddRangeAsync(item);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task<int> AsyncRangeUpdate(List<T> item)
        {
            db.Set<T>().UpdateRange(item);
            return await db.SaveChangesAsync();
        }
    }
}
